import { LANG, TAGS_VIEW } from '@/constant'
import { getItem, setItem } from '@/utils/storage'

export default {
  namespaced: true,
  state: () => ({
    sidebarOpened: true,
    language: getItem(LANG) || 'zh',
    tagsViewList: getItem(TAGS_VIEW) || []
  }),
  mutations: {
    triggleSidebarOpened (state) {
      state.sidebarOpened = !state.sidebarOpened
    },
    setLanguage (state, lang) {
      setItem(LANG, lang)
      state.language = lang
    },
    // 添加tags
    addTagsViewList (state, tag) {
      const isFind = state.tagsViewList.find((item) => {
        return item.path === tag.path
      })
      // 去重，不能重复添加tag
      if (!isFind) {
        state.tagsViewList.push(tag)
        setItem(TAGS_VIEW, state.tagsViewList)
      }
    },
    // 为指定的tag修改title
    changeTagsView (state, { index, tag }) {
      state.tagsViewList[index] = tag
      setItem(TAGS_VIEW, state.tagsViewList)
    },
    /**
     * 删除tag
     * type: 'other' || 'right' || 'index' ;
     * payload
     */
    removeTagsView (state, payload) {
      switch (payload.type) {
        case 'index':
          // 删除当前
          state.tagsViewList.splice(payload.index, 1)
          break
        case 'other':
          // 删除其他
          state.tagsViewList.splice(
            payload.index + 1,
            state.tagsViewList.length - payload.index + 1
          )
          state.tagsViewList.splice(0, payload.index)
          break
        case 'right':
          // 删除右边
          state.tagsViewList.splice(
            payload.index + 1,
            state.tagsViewList.length - payload.index + 1
          )
          break
      }
      setItem(TAGS_VIEW, state.tagsViewList)
    }
  }
}
